<template>
  <card-group-solt
  @handleClick="changeTab"
  :activeName="activeName"
  :tabPanes="tabPanes"
  :cardLoading="loading">
    <template
    :slot="'search'">
      <search
      :type="activeName">
        <template :slot="'select'">
          <div>
            <el-select size="mini" style="width: 80px;margin-left: 10px;flex: 3;color: #000;" class="select" v-model.trim="selectVal" :placeholder="$t('public.all')">
              <el-option class="ss-el-option" v-for="item in search[activeName].isChildren.select"
                         @click.native="handleClick(item.value, item.disabled, item)"
                         :label="item.label" :value="item.value" :disabled="item.disabled"
                         :class="item.sortClass"></el-option>
            </el-select>
             <!--<v-select-->
             <!--:customer="true"-->
             <!--:selectOptions="search[activeName].isChildren.select"-->
             <!--:form="search[activeName].isChildren.nomalForm"-->
             <!--@quickSelect="handlerQuickSelect"></v-select>-->
          </div>
        </template>
        <template :slot="'inputSearch'">
          <input-search
          :placeHolder="search.placeHolder"
          :form="search[activeName].isChildren.nomalForm"
          @quickSearch="handlerQuickSearch"></input-search>
        </template>
        <template :slot="'advancedSearch'">
          <advanced-search
            ref="advSearch"
            :type="type"
            :pickerName="'customerDate'"
            :adv="search[activeName].isChildren.adv"
            :formItemsConfig="formItemsConfigs[this.activeName]"
            @selectChange="handlerSelectChange"
            @advSearch="advSearch"
            @confirmNewItemsConfig="handleConfirmNewItemsConfig"
          >
          </advanced-search>
        </template>
        <template :slot="'changeCardStyle'">
          <div @click="changeToNewCustomer" style="position:absolute;top:10px;right:40px;cursor:pointer">
            <i class='iconfont icon-qiehuanshitu' style="font-size:18px;"></i>
            <div v-if='!getNoviceKeyStatus.customerViewSwitch' style="position: absolute;top: -15px;right:7px ;padding-bottom: 10px;z-index: 100;cursor: default;">
              <popover-novice
                style="position: absolute;right: -25px;top: 15px;"
                noviceKey = 'customerViewSwitch'
                :noviceHtml = "{title: '', text: '视图切换功能：可根据个人习惯选择切换卡片视图，列表视图'}"
                @updateGuidanceSuccess="updateGuidanceSuccess('click')"
              ></popover-novice>
            </div>
          </div>
        </template>
        <template :slot="'dropdownSelect'">
          <dropdown-menu
          :newEmptySeat="newEmptySeat"
          :tabType="'customer'">

          </dropdown-menu>
        </template>
        <template :slot="'advSchBadge'">
          <advSchBadge
            :badge="search[activeName].isChildren.adv.badgeList"
            @removeBadge="removeBadge">
          </advSchBadge>
        </template>
        <template :slot="'CustRefresh'">
          <refresh
          @refresh="handleRefresh" :class="'positionClass'"></refresh>
        </template>
      </search>
    </template>
    <template
    :slot="'cardList'">
      <customer-card
        :cardList="cardList"
        :count="count"
        :allCount="allCount"
        :qu="qu"
        :type="type"
        :tabType="activeName"
        :clearChecked="clearChecked"
        @allCountClear="allCountClear"
        :condition="search[activeName].isChildren.lastQuery">
      </customer-card>
    </template>
    <template slot="pagination">
      <pagination
        :customerShow="true"
        :small="true"
        :currentPage="currentPage"
        :count="count"
        :moreFlag="moreFlag"
        :allCount="allCount"
        :type="type"
        :tabType="activeName"
        @turnPage="turnPage"
        :totalPage="totalPage"
        @getAllCount="getAllCount"
      >
      </pagination>
    </template>
  </card-group-solt>
</template>
<script>
  import CardGroupSolt from '@/components/public-modules/card/NewIndex.vue'
  import CustomerCard from './CustomerCard.vue'
  import Search from '@/components/public-modules/card/search/NewIndex.vue'
  import Select from '@/components/public-modules/card/search/Select'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import DropdownMenu from '@/components/public-modules/card/search/DropdownMenu.vue'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced1Search'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Refresh from '../../ui-modules/icon/Refresh'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
  import popoverNovice from '@/components/public-modules/novice-boot/popoverNovice.vue'
  import { deepClone, getFormatDateTime, getDateTime } from '@/utils/m7Utils'
  import { sortCustomFields } from '@/utils/customerUtils.js'
  export default {
    name: 'CustCardGroup',
    data () {
      return {
        getNoviceKeyStatus: {'customerViewSwitch': false},
        selectVal: '',
        isFirst: null,
        loading: true,
        // 最大页数基数
        pages: 0,
        PAGE_SIZE: 10,
        allCount: 0,
        qu: {},
        activeName: 'customer_my',
        type: 'customer',
        clearChecked: '',
        newEmptySeat: false,
        tabPanes: [
          {name: this.$t('customer.customerMy'), type: 'customer_my'},
          {name: this.$t('customer.customerPlan'), type: 'customer_plan'},
          {name: this.$t('customer.customerAll'), type: 'customer_all'}
        ],
        search: {
          isSearch: false,
          placeHolder: this.$t('customer.enterNameOrPhoneForQuery'),
          customer_my: {
            pagination: {
              small: true,
              currentPage: 1
            },
            show: true,
            isChildren: {
              lastQuery: null,
              rel: true,
              select: [],
              nomal: true,
              refresh: true,
              nomalForm: { value: '', query: '' },
              adv: {
                form: { categoryId: null, status: null, name: null, phone: null, actionType: [], custsource1: null, province: null, city: null, lastUpdateTime: [], createTime: [], batchNo: null, notifyTime: [], noContactedTime: [], CallTime: [], noCallTime: [], custom: {} },
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          },
          customer_plan: {
            pagination: {
              small: true,
              currentPage: 1
            },
            show: true,
            isChildren: {
              lastQuery: null,
              rel: true,
              select: [],
              nomal: true,
              refresh: true,
              nomalForm: { value: '', query: '' },
              adv: {
                form: { categoryId: null, status: null, name: null, phone: null, actionType: [], custsource1: null, province: null, city: null, district: null, lastUpdateTime: [], createTime: [], batchNo: null, noContactedTime: [], CallTime: [], noCallTime: [], notifyTime: [], custom: {} },
                advSearchOptions: {
                  localed: [],
                  custom: []
                },
                badgeList: {}
              }
            }
          },
          customer_all: {
            pagination: {
              small: true,
              currentPage: 1
            },
            show: true,
            isChildren: {
              lastQuery: null,
              rel: true,
              select: [],
              nomal: true,
              refresh: true,
              nomalForm: { value: '', query: '' },
              adv: {
                form: { categoryId: null, status: null, name: null, phone: null, actionType: [], custsource1: null, province: null, city: null, district: null, lastUpdateTime: [], createTime: [], batchNo: null, notifyTime: [], ownercom: null, owner: null, ownerdep: null, noContactedTime: [], CallTime: [], noCallTime: [], custom: {} },
                advSearchOptions: {
                  localed: [],
                  custom: []
                }
              },
              badgeList: {}
            }
          }
        },
        card: {
          call: {
            count: ''
          },
          myCall: {
            count: ''
          },
          allCall: {
            count: ''
          }
        },
        formItemsConfigs: {}
      }
    },
    components: {
      CustomerCard,
      Search,
      'v-select': Select,
      CardGroupSolt,
      InputSearch,
      DropdownMenu,
      AdvancedSearch,
      Refresh,
      Pagination,
      AdvSchBadge,
      popoverNovice
    },
    beforeMount () {
      this.searchInit()
      // 高级搜索自定义布局配置
      this.updateGuidanceSuccess()
      this.$store.dispatch('getAdvSearchConfig', {
        searchType: 'CustCardGroup'
      }).then((configs) => {
        this.formItemsConfigs = configs || {}
      })
    },
    computed: {
      noticeBusJump () {
        return this.$store.state.noticeCustJump.random
      },
      cardObj () {
        return this.$store.state.customer.customerList[this.activeName] || {}
      },
      cardList () {
        let cardObj = this.cardObj
        let list = cardObj.list || []
        return JSON.parse(JSON.stringify(list))
      },
      moreFlag () {
        if (this.cardObj.more) {
          return true
        } else {
          return
        }
      },
      count () {
        return this.cardObj.count
      },
      currentPage () {
        return this.search[this.activeName].pagination.currentPage
      },
      totalPage () {
        return Math.ceil(this.count / this.PAGE_SIZE) || 0
      },
      // 当值发生改变刷新左侧列表
      refreshLeftcard () {
        return this.$store.state.customer.transCache.refreshLeft
      },
      quickSearchList () {
        return this.$store.state.customer.quickSearchList
      },
      addSuccess () {
        return this.$route.query
      }
    },
    watch: {
      noticeBusJump () {
        let data = this.$store.state.noticeCustJump
        if (data.module === 'customer' && this.isFirst) {
          this.routeToMe()
        }
      },
      // 客户添加成功跳转到相应的模块
      addSuccess (to, from) {
        if (to.addSuccess) {
          let page = 1
          let morePage = page >= this.pages ? Math.floor(page / this.pages + 1) : 1
          this.activeName = to.addSuccess
          let query = {
            menu: this.activeName,
            page: page,
            morePage: morePage,
            limit: this.PAGE_SIZE
          }
          this.search[this.activeName].isChildren.lastQuery = query
          this.turnPage(page)
        }
      },
      refreshLeftcard () {
        let _page = this.search[this.activeName].pagination.currentPage
        // 刷新左侧列表掉翻页方法
        this.turnPage(_page)
      },
      quickSearchList: {
        handler: function (current) {
          // 快捷搜索 - select
          this.$store.dispatch('getCache', { type: 'custTmpls' }).then((custTmpls) => {
            if (custTmpls.length <= 0) { // 新开的账户，没有数据
              this.$data.newEmptySeat = true
              return
            } else {
              this.$data.newEmptySeat = false
            }
            let custTmpl = custTmpls[0]
            this.tabPanes.forEach(tabPane => {
              let quickSelect = [{ label: this.$t('public.all'), value: '' }]
              if (tabPane.type === 'customer_plan') {
                quickSelect.push({ label: this.$t('customer.todayContactPlan'), value: 'totalNotify' })
                quickSelect.push({ label: this.$t('customer.myExecutorPlan'), value: 'executor' })
              }
              // 客户状态
              for (let key in custTmpl.status) {
                quickSelect.push({ label: custTmpl.status[key], value: key })
              }
              // 自定义快捷搜索
              current.list.forEach(quickSearchTmpl => {
                if (quickSearchTmpl.menu === tabPane.type) {
                  quickSelect.push({ label: quickSearchTmpl.kName, isCustomize: true, query: quickSearchTmpl.query, value: quickSearchTmpl._id })
                }
              })
              this.search[tabPane.type].isChildren.select = quickSelect
            })
          })
        },
        deep: true
      }
    },
    deactivated () {
      this.isFirst = false
    },
    activated () {
      if (this.isFirst === null) {
        // 第一次进入组件时 currentPage未null 不执行routeToMe函数，在beforeMount里执行
        return
      }
      this.isFirst = true
      this.routeToMe()
    },
    methods: {
      updateGuidanceSuccess (type) {
        if (type === 'click') {
          this.getNoviceKeyStatus = { 'customerViewSwitch': true }
        } else {
          let guidance = this.$getCache('guidance')
          this.getNoviceKeyStatus = guidance || { 'customerViewSwitch': true }
        }
      },
      changeToNewCustomer () {
        this.$store.commit('IS_NEW_CARD_STYLE', {type: 'customer', data: true})
        this.$store.dispatch('updateViewSwitch', {module: 'customer', status: 'new'})
      },
      handleClick (value, disabled, item) {
        if (!disabled) {
          if (item.isCustomize) {
            this.handlerQuickSelect(item.query)
          } else {
            this.handlerQuickSelect(value)
          }
        }
      },
      handleLocaledOptions (custTmpl, custCategorysCache) {
        let statuses = [{ label: this.$t('public.all'), value: '' }]
        for (let key in custTmpl.status) {
          statuses.push({ label: custTmpl.status[key], value: `${key}__${custTmpl.status[key]}` })
        }
        let sources = [{ label: this.$t('public.all'), value: '' }, { label: this.$t('customer.noSource'), value: `NA__${this.$t('customer.noSource')}` }, ...custTmpl.source.map(source => ({ label: source.name, value: `${source.key}__${source.name}` }))]
        let custCategorys = [{ label: this.$t('public.all'), value: '' }, ...custCategorysCache.map(category => ({ label: category.cName, value: `${category._id}__${category.cName}` }))]

        let localedOptions = [
          { label: this.$t('customer.categorySource'), filterable: true, name: 'categoryId', inputType: 'select', data: custCategorys },
          { label: this.$t('customer.custStatus'), filterable: true, name: 'status', inputType: 'select', data: statuses },
          { label: this.$t('business.customerName'), name: 'name', inputType: 'input' },
          { label: this.$t('customer.custCall'), name: 'phone', inputType: 'input' },
          { label: this.$t('customer.hasContactPlan'), name: 'actionType', inputType: 'checkbox', data: [{ label: this.$t('public.yes'), value: `date__${this.$t('customer.hasContactPlan')}` }] },
          { label: this.$t('customer.dataSource'), filterable: true, name: 'custsource1', inputType: 'select', data: sources },
          { label: this.$t('public.provinceCity'), name: 'area', inputType: 'area', provinceName: 'province', provinceValue: this.search[this.activeName].isChildren.adv.form.province, cityName: 'city', cityValue: this.search[this.activeName].isChildren.adv.form.city, districtName: 'district', districtValue: this.search[this.activeName].isChildren.adv.form.district },
          { label: this.$t('km.updateTime'), name: 'lastUpdateTime', inputType: 'time' },
          { label: this.$t('public.createTime'), name: 'createTime', inputType: 'time' },
          { label: this.$t('customer.noContactedTime'), name: 'noContactedTime', inputType: 'time' },
          { label: this.$t('customer.noCallTime'), name: 'noCallTime', inputType: 'time' },
          { label: this.$t('customer.CallTime'), name: 'CallTime', inputType: 'time' },
          { label: this.$t('customer.importBatch'), name: 'batchNo', inputType: 'input' },
          { label: this.$t('customer.contactPlan.contactPlanTime'), name: 'notifyTime', inputType: 'time' }
        ]
        return localedOptions
      },
      handleCustomOptions (custTmpl) {
        let customForm = {}
        let customOptions = []
        let sortedCustomFields = sortCustomFields(custTmpl.custom_fields)
        sortedCustomFields.forEach(customField => {
          // 启用的
          if(customField.status !== 'stop') {
            let option = { label: customField.name, name: customField._id }
            if (customField.type === 'single') {
              option.inputType = 'input'
            } else if (customField.type === 'multi') {
              option.inputType = 'textarea'
            } else if (customField.type === 'number') {
              option.inputType = 'input'
              option.validateType = 'Number'
            } else if (customField.type === 'dropdown') {
              if (customField.dic) {
                option.inputType = 'cascader'
                option.data = customField.dic
                option.props = { multiple: true , 'collapse-tags':true, clearable: true}
              } else {
                option.inputType = 'select'
                option.data = []
                for (let key in customField.choices) {
                  let label = customField.choices[key] || ' '
                  option.data.push({ label, value: `${key}__${customField.choices[key]}` })
                }
              }
            } else if (customField.type === 'checkbox' || customField.type === 'radio') {
              option.inputType = customField.type
              option.data = []
              for (let key in customField.choices) {
                option.data.push({ label: customField.choices[key], value: `${key}__${customField.choices[key]}` })
              }
            } else {
              option.inputType = customField.type
            }
  
            customOptions.push(option)
  
            if (customField.type === 'checkbox') {
              customForm[customField._id] = []
            } else if (customField.type === 'date') {
              customForm[customField._id] = ''
            } else if (customField.type === 'dropdown' && !customField.dic) {
              customForm[customField._id] = {$in: []}
            } else {
              customForm[customField._id] = null
            }
          }
        })
        let _obj = {
          customForm: customForm,
          customOptions: customOptions
        }
        return _obj
      },
      searchInit () {
        Promise.all([
          this.$store.dispatch('getCache', { type: 'custCategorys' }),
          this.$store.dispatch('getCache', { type: 'custTmpls' }),
          this.$store.dispatch('getCache', { type: 'quickSearchTmpls' })
        ]).then(([custCategorysCache, custTmpls, quickSearchTmpls]) => {
          if (custTmpls.length <= 0) { // 新开的账户，没有数据
            this.$data.newEmptySeat = true
            return
          } else {
            this.$data.newEmptySeat = false
          }
          let custTmpl = custTmpls[0]
          // 处理固定查询字段
          let localedOptions = this.handleLocaledOptions(custTmpl, custCategorysCache)
          let isFieldAdded = (fieldName) => fieldName === 'province' || fieldName === 'city' || fieldName === 'name' || fieldName === 'phone' || fieldName === 'district'
          let stableFieldsDefaultValue = {}
          custTmpl.stable_fields.forEach(stableField => {
            if (stableField.search && !isFieldAdded(stableField.name)) {
              localedOptions.push({ label: stableField.value, name: stableField.name, inputType: 'input' })
              stableFieldsDefaultValue[stableField.name] = ''
            }
          })
          // 处理自定义字段
          let _obj = this.handleCustomOptions(custTmpl)
          this.tabPanes.forEach(tabPane => {
            let localedOptionsCopy = deepClone(localedOptions)
            let quickSelect = [{ label: this.$t('public.all'), value: '' }]
            if (tabPane.type === 'customer_plan') {
              quickSelect.push({ label: this.$t('customer.todayContactPlan'), value: 'totalNotify' })
              quickSelect.push({ label: this.$t('customer.myExecutorPlan'), value: 'executor' })
            }
            if (tabPane.type === 'customer_all') {
              localedOptionsCopy.push({ label: this.$t('customer.owner'), name: 'owner', inputType: 'owner' })
            }
            // 客户状态
            for (let key in custTmpl.status) {
              quickSelect.push({ label: custTmpl.status[key], value: key })
            }
            // 自定义快捷搜索
            quickSearchTmpls.forEach(quickSearchTmpl => {
              if (quickSearchTmpl.menu === tabPane.type) {
                quickSelect.push({ label: quickSearchTmpl.kName, isCustomize: true, query: quickSearchTmpl.query, value: quickSearchTmpl._id })
              }
            })
            this.search[tabPane.type].isChildren.select = quickSelect
            this.search[tabPane.type].isChildren.adv.form = Object.assign({}, this.search[tabPane.type].isChildren.adv.form, stableFieldsDefaultValue)
            this.search[tabPane.type].isChildren.adv.advSearchOptions.localed = localedOptionsCopy
            this.search[tabPane.type].isChildren.adv.advSearchOptions.custom = deepClone(_obj.customOptions)
            this.search[tabPane.type].isChildren.adv.form.custom = deepClone(_obj.customForm)
          })
          this.isFirst = true
          console.log('init')
          this.routeToMe(true)
        })
      },
      /**
       * /
       * @param  {[type]} store   [vue store模块]
       * @param  {[type]} tabName [对应卡片模块 1我的客户 2联系计划 3全部]
       * @param  {[type]} query   [description]
       * @return {[type]}         [description]
       */
      allCountClear () {
        this.allCount = 0
        // 客户模块操作页码不重置
        // this.search[this.activeName].pagination.currentPage = 1
      },
      routeToMe (isBeforeMount) {
        console.log(this.$route)
        let query = this.$route.query
        if (query.active) {
          if (query.id) {
            this.clearSearchQuery()
            this.activeName = query.active
            if (query.selectVal) {
              this.search[this.activeName].isChildren.nomalForm.value = 'executor'
            }
            this.fetchDataQuickSelect(query.selectVal, query.id)
//              this.changeTab(query.active)
          } else {
            this.changeTab(query.active)
          }
        } else if (isBeforeMount) {
          this.changeTab(this.activeName, true)
        }
      },
      getCustList (store, tabName, query) {
        let _data = deepClone(query)
        _data.queryCount = true
        this.qu = _data
        return store.dispatch('queryCustomerList', query).then((resp) => {
          if (query.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          if (resp && resp.success) {
            console.log('qingqiu')
            console.log(resp)
            // 判定是否是获取真实的count,如果是获取的是真实的count，则不进行处理
            if (!query.queryCount) {
              // 如果返回的列表不为空，则直接保留在当前页，不做任何处理
              // 如果返回的列表为空，则有两种情况，如果有多于 则返回到第一页，否则返回到最后一页
              if (resp.list.length === 0) {
                if (resp.more) {
                  this.turnPage(1)
                } else {
                  // 算出最后一页的页数
                  let page = Math.ceil(resp.count / query.limit)
                  if (resp.count === 0) {
                    // 第一页且count为0是不再发请求
                    this.search[this.activeName].pagination.currentPage = 1
                    return
                  }
                  this.turnPage(page)
                }
              }
            }
          }
//          return Promise.resolve()
          return resp
        })
      },
      getAllCount () {
        this.allCount = 0
        let form = this.qu
        form.queryCount = true
        form.searchAllCount = true // 此参数是防止vuex的值被改动
        let activeName = this.activeName
        let more = false
        this.getCustList(this.$store, this.activeName, form).then((resp) => {
          delete this.qu.searchAllCount
          if (resp && resp.success) {
            this.allCount = resp.count
            this.$store.commit('customer/SET_CUSTOMER_MORE', {activeName, more})
            this.loading = false
          }
        })
      },
      handleRefresh () {
        let _page = this.search[this.activeName].pagination.currentPage
        // 刷新当前页
        this.turnPage(_page)
        // this.advSearch()
      },
      // 清空搜索条件
      clearSearchQuery () {
        this.selectVal = ''
        let currentTab = this.search[this.activeName]
        currentTab.pagination.currentPage = 1
        for (let key in currentTab.isChildren.adv.form) {
          if (key !== 'custom') {
            if (Array.isArray(currentTab.isChildren.adv.form[key])) {
              currentTab.isChildren.adv.form[key] = []
            } else if (currentTab.isChildren.adv.form.custom[key] && currentTab.isChildren.adv.form.custom[key].$in) {
              currentTab.isChildren.adv.form.custom[key] = {$in: []}
            } else {
              currentTab.isChildren.adv.form[key] = null
            }
          } else {
            for (let key in currentTab.isChildren.adv.form.custom) {
              if (Array.isArray(currentTab.isChildren.adv.form.custom[key])) {
                currentTab.isChildren.adv.form.custom[key] = []
              } else if (currentTab.isChildren.adv.form.custom[key] && currentTab.isChildren.adv.form.custom[key].$in) {
                currentTab.isChildren.adv.form.custom[key] = {$in: []}
              } else {
                currentTab.isChildren.adv.form.custom[key] = null
              }
            }
          }
        }
        this.search[this.activeName].isChildren.adv.badgeList = null
        for (let key in this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm[key] = null
        }
        this.search[this.activeName].isChildren.lastQuery = null
        this.$refs.advSearch.resetForm()
      },
      routerEnter () {
        this.$store.commit('BLANK', this.activeName)
      },
      // 切换tab 我的客户 联系计划 全部模块时更新相关tab的展示列表
      changeTab (tabName) {
        this.allCount = 0
        this.activeName = tabName
        this.$store.commit('BLANK', tabName)
        this.loading = true
        this.search.isSearch = true
        // 清空搜索条件
        this.clearSearchQuery()
        let queryData = {
          menu: tabName,
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        }
        this.search[this.activeName].isChildren.lastQuery = queryData
        // 请求客户列表
        this.getCustList(this.$store, this.activeName, queryData).then(() => {
          this.loading = false
        })
      },
      // 卡片列表翻页刷新列表
      turnPage (pageNum) {
        this.allCount = 0
        // if (this.search.isSearch && pageNum < 2) {
        //   this.search.isSearch = false
        //   return
        // }
        this.search.isSearch = false
        this.loading = true
        let morePage = pageNum >= this.pages ? Math.floor(pageNum / this.pages + 1) : 1
        let queryData = Object.assign({}, this.search[this.activeName].isChildren.lastQuery, { page: pageNum, morePage })
        this.search[this.activeName].pagination.currentPage = pageNum
        this.getCustList(this.$store, this.activeName, queryData).then(() => {
          this.loading = false
        })
      },
      fetchDataQuickSelect (value, id) {
        this.allCount = 0
        this.loading = true
        // 清除高级搜索项
        this.search[this.activeName].isChildren.adv.badgeList = {}
        // this.clearSearchQuery()
        this.search.isSearch = true
        this.search[this.activeName].isChildren.nomalForm.value = value
        let query = {
          menu: this.activeName,
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        }
        if (id) {
          query._id = id
        }
        if (value) {
          Object.assign(query, (typeof value === 'object') ? value : { status: value })
        }
        if (this.search[this.activeName].isChildren.nomalForm.query) {
          query.combox = this.search[this.activeName].isChildren.nomalForm.query
        }
        for (let key in query) {
          if (query[key] instanceof Object && !(query[key] instanceof Array)) {
            let date = {}
            for (let datekey in query[key]) {
              if (datekey === 'JGx0') {
                date['$lt'] = query[key][datekey]
              } else if (datekey === 'JGd0') {
                date['$gt'] = query[key][datekey]
              }
            }
            query[key] = date
          }
        }
        this.search[this.activeName].pagination.currentPage = 1
        this.search[this.activeName].isChildren.lastQuery = query
        this.getCustList(this.$store, this.activeName, query).then((resp) => {
          console.log('接口毁掉')
          console.log(resp)
          if (id) {
            if (resp && resp.list.length !== 0) {
              let _id = resp.list[0]._id
              this.$router.push('/index/customer/' + this.activeName + '/' + _id)
              this.$store.commit('customer/REFRESH_CUST_RIGHT', Math.random())
            } else {
              this.$router.push('/index/customer')
              this.changeTab(this.activeName)
              this.$store.commit('BLANK', this.activeName)
            }
          }
          this.loading = false
        })
      },
      // 快捷搜索 - select
      handlerQuickSelect (value) {
        this.fetchDataQuickSelect(value)
      },
      // 快捷搜索 - input
      handlerQuickSearch (value) {
        this.allCount = 0
        this.loading = true
        this.search.isSearch = true
        // 清除高级搜索项
        this.search[this.activeName].isChildren.adv.badgeList = {}
        // this.clearSearchQuery()
        this.search[this.activeName].isChildren.nomalForm.query = value
        let query = {
          menu: this.activeName,
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        }
        if (value) {
//          if (this.$route.query.custName) {
//            query._id = this.$route.path.split('/')[4].split('?')[0]
//            this.search[this.activeName].isChildren.nomalForm.query = ''
//            this.search[this.activeName].isChildren.nomalForm.value = ''
//          } else {
//            query.combox = value
//          }
          query.combox = value
        }
        if (this.search[this.activeName].isChildren.nomalForm.value) {
          let selectValue = this.search[this.activeName].isChildren.nomalForm.value
          Object.assign(query, (typeof selectValue === 'object') ? selectValue : { status: selectValue })
        }
        this.search[this.activeName].pagination.currentPage = 1
        this.search[this.activeName].isChildren.lastQuery = query
        this.getCustList(this.$store, this.activeName, query).then(() => {
          this.loading = false
        })
      },
      /**
       * [handlerSelectChange description]
       * @param  {[type]} selectObj [
       * selectName 传给后台的属性名
       * selectValue.value  选中的值 => 传给后台
       * selectValue.label 选中的label =>回显的字符串
       * ]
       * @return {[type]}           [description]
       */
      handlerSelectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue
        let form = this.search[this.activeName].isChildren.adv.form
        // 省市的数据拼接
        if (selectName === 'areaLinkage') {
          for (let key in selectValue) {
            form[key] = selectValue[key] ? selectValue[key] : ''
          }
        }
        // 级联的数据处理
        if (selectName === 'cascader') {
          if (selectObj.custom) {
            form.custom[selectObj.name] = selectValue
          } else {
            form[selectObj.name] = selectValue
          }
        }
        // 公海的数据处理
        if (selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') {
          form.ownercom = null
          form.owner = null
          form.ownerdep = null
          form[selectName] = selectValue
        }
      },
      /**
       * [advSearchBack 高级搜索回显]
       * @param  {[type]} searchQuery [需要回显的参数]
       * @return {[type]}             [description]
       */
      advSearchBack (searchQuery) {
        let tmpObj = {}
        for (let key in searchQuery) {
          let value = searchQuery[key]
          if (value && typeof value === 'string') {
            if (value.match(/__/)) {
              let valSplit = value.split('__')
              tmpObj[key] = valSplit[1]
              searchQuery[key] = valSplit[0]
            } else {
              tmpObj[key] = value
            }
          }
          if (value && Array.isArray(value) && value.length > 0) {
            let tmpArr = []
            let tmpArr2 = []
            let nameArr= []
            for (let i = 0; i < value.length; i++) {
              if(Array.isArray(value[i])){
                let arr =  []
                let obj = []
                value[i].forEach(item=>{
                  let valSplit = item.split('__')
                  arr.push(valSplit[1])
                  obj.push(valSplit[0])
                })
                tmpArr2.push(obj)
                nameArr.push(arr)
              }else{
                let valSplit = value[i].split('__')
                tmpArr.push(valSplit[1])
                tmpArr2.push(valSplit[0])
              }
            }
            if(nameArr.length>0){
              nameArr.forEach(val=>{
                tmpArr += val.join(' ') + ';'
              })
              tmpArr = tmpArr.substring(0, tmpArr.lastIndexOf(";"));
              tmpObj[key] = tmpArr
              searchQuery[key] = tmpArr2
            }else{
              tmpObj[key] = tmpArr.join(';')
              searchQuery[key] = tmpArr2
            }
          }

          if (value && value.$in && Array.isArray(value.$in) && value.$in.length > 0) {
            let tmpArr = []
            let tmpArr2 = []
            for (let i = 0; i < value.$in.length; i++) {
              let valSplit = value.$in[i].split('__')
              tmpArr.push(valSplit[1])
              tmpArr2.push(valSplit[0])
            }
            tmpObj[key] = tmpArr.join(' ')
            searchQuery[key].$in = tmpArr2
          }

          if (value && value.$in && Array.isArray(value.$in) && value.$in.length === 0) {
            searchQuery[key] = null
          }
        }

        return tmpObj
      },
      /**
       * [advSearch 高级搜索]
       * @param  {[type]} reset [判断是否重置高级搜索参数]
       * @return {[type]}       [description]
       */
      advSearch (reset) {
        window._hmt && window._hmt.push(['_trackEvent', '其他统计', this.activeName + ' 高级搜索'])
        this.allCount = 0
        this.loading = true
        this.search.initSearch = true
        if (reset) {
          this.clearSearchQuery()
        }
        // 清空快捷搜索字段
        this.search[this.activeName].isChildren.nomalForm.query = ''
        this.search[this.activeName].isChildren.nomalForm.value = ''
        let form = this.search[this.activeName].isChildren.adv.form
        let searchQuery = deepClone(form)
        // 处理deepClone导致Date对象丢失
        for (let key in form.custom) {
          if (form.custom[key] instanceof Date) {
            searchQuery.custom[key] = new Date(form.custom[key].getTime())
          }
        }
        let custom = searchQuery.custom
        let createTime = form.createTime
        let lastUpdateTime = form.lastUpdateTime
        let notifyTime = form.notifyTime
        let noContactedTime = form.noContactedTime
        let noCallTime = form.noCallTime
        let CallTime = form.CallTime
        // 电话
        if (searchQuery.phone) {
          let tel = searchQuery.phone
          searchQuery['phone.tel'] = tel
          delete searchQuery.phone
        }

        // 是否建立联系计划
        if (searchQuery.actionType.length > 0) {
          searchQuery.actionType = searchQuery.actionType[0]
        }

        // 创建时间
        if (createTime) {
          if (createTime[0]) {
            searchQuery.createTime_begin_date = getFormatDateTime(createTime[0])
          }
          if (createTime[1]) {
            searchQuery.createTime_end_date = getFormatDateTime(createTime[1])
          }
          delete searchQuery.createTime
        }

        // 更新时间
        if (lastUpdateTime) {
          if (lastUpdateTime[0]) {
            searchQuery.lastUpdateTime_begin_date = getFormatDateTime(lastUpdateTime[0]).substring(0, 16)
          }
          if (lastUpdateTime[1]) {
            searchQuery.lastUpdateTime_end_date = getFormatDateTime(lastUpdateTime[1]).substring(0, 16)
          }
          delete searchQuery.lastUpdateTime
        }

        // 最近未联系客户时间
        if (noContactedTime) {
          if (noContactedTime[0]) {
            searchQuery.noContactedTime_begin = getFormatDateTime(noContactedTime[0]).substring(0, 16)
          }
          if (noContactedTime[1]) {
            searchQuery.noContactedTime_end = getFormatDateTime(noContactedTime[1]).substring(0, 16)
          }
          delete searchQuery.noContactedTime
        }
        // 最近未通话客户时间
        if (noCallTime) {
          if (noCallTime[0]) {
            searchQuery.noCallTime_begin_date = getFormatDateTime(noCallTime[0]).substring(0, 16)
          }
          if (noCallTime[1]) {
            searchQuery.noCallTime_end_date = getFormatDateTime(noCallTime[1]).substring(0, 16)
          }
          delete searchQuery.noCallTime
        }
        // 通话时间
        if (CallTime) {
          if (CallTime[0]) {
            searchQuery.CallTime_begin_date = getFormatDateTime(CallTime[0]).substring(0, 16)
          }
          if (CallTime[1]) {
            searchQuery.CallTime_end_date = getFormatDateTime(CallTime[1]).substring(0, 16)
          }
          delete searchQuery.CallTime
        }
        // 联系时间
        if (notifyTime) {
          if (notifyTime[0]) {
            searchQuery.notifyTime_begin_date = getFormatDateTime(notifyTime[0])
          }
          if (notifyTime[1]) {
            searchQuery.notifyTime_end_date = getFormatDateTime(notifyTime[1])
          }
          delete searchQuery.notifyTime
        }
        let _customerArr = this.search[this.activeName].isChildren.adv && this.search[this.activeName].isChildren.adv.advSearchOptions.custom
        // 自定义字段
        for (let key in custom) {
          // 处理自定义字段中的日期
          if (custom[key] instanceof Array) {
            for (let i = 0; i < _customerArr.length; i++) {
              if (_customerArr[i].name === key && _customerArr[i].inputType === 'date') {
                let _str = ''
                if (custom[key][0]) {
                  _str += getDateTime(custom[key][0], 'date')
                }
                if (custom[key][1]) {
                  _str += '_' + getDateTime(custom[key][1], 'date')
                }
                searchQuery[key + '_customDate'] = _str
                delete custom[key]
                delete searchQuery[key]
              } else if (_customerArr[i].name === key && _customerArr[i].inputType === 'datetime') {
                let _str = ''
                if (custom[key][0]) {
                  _str += getFormatDateTime(custom[key][0])
                }
                if (custom[key][1]) {
                  _str += '_' + getFormatDateTime(custom[key][1])
                }
                searchQuery[key + '_customDateTime'] = _str
                delete custom[key]
                delete searchQuery[key]
              } else {
                searchQuery[key] = custom[key]
              }
            }
            continue
          } else {
            searchQuery[key] = custom[key]
          }
        }
        delete searchQuery.custom

        let tempObj = this.advSearchBack(searchQuery)
        this.search[this.activeName].isChildren.adv.badgeList = tempObj

        Object.assign(searchQuery, {
          menu: this.activeName,
          page: 1,
          morePage: 1,
          limit: this.PAGE_SIZE
        })
        console.log(searchQuery,'ssearchquery1')
        this.search[this.activeName].pagination.currentPage = searchQuery.page
        this.search[this.activeName].isChildren.lastQuery = searchQuery
        this.getCustList(this.$store, this.activeName, searchQuery).then(() => {
          this.loading = false
        })
      },
      /**
       * [removeBadge description]
       * 移除高级搜索的回显项
       * @return {[type]} [description]
       */
      removeBadge () {
        this.advSearch(true)
        this.clearChecked = Math.random() + ''
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs[this.activeName] = formItemsConfig

        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'CustCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      }
    }
  }
</script>
